/************************************************************************
 * The code is owned by mainframer.cn and Shang Tao
 * Without aproval of mainframer.cn and Shang Tao, remove the copyright
 * infomation is regarded invassion of proprietary copyright
 ***********************************************************************/
package com.mr.qa.action;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessages;
import org.hibernate.Transaction;

import com.mr.qa.GlobalConfigs;
import com.mr.qa.UserSession;
import com.mr.qa.UserSessionUtil;
import com.mr.qa.bo.User;
import com.mr.qa.dao.impl.UserDAO;
import com.mr.qa.exception.QaException;
import com.mr.qa.form.UserForm;
import com.mr.qa.util.HibernateSessionFactory;


public abstract class BaseAction extends Action
{
        private static final Log log = LogFactory.getLog(BaseAction.class);
        public static final String ORIGINAL_URL_NAME = "originalUrl";
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception 
	{
	    UserSession us = UserSessionUtil.getUserSession(request);        
            if(GlobalConfigs.isApplicationUnderUpdate)
            {
                if(us == null || "0".equals(us.getType()))
                    return mapping.findForward("systemunderchange");
            }
	    String originalUrl = "";
	    String action = "";
            if(form instanceof UserForm)
            {
                originalUrl = ((UserForm)form).getOriginalUrl();
                action = ((UserForm)form).getAction();
            }
            if(!"login".equals(action))
            {
                if(originalUrl == null || originalUrl.length() == 0)
                    saveOriginalUrl(request);
                else
                    saveOriginalUrl(request,originalUrl);
            }
            else
            {
                if(originalUrl != null && originalUrl.length() > 0)
                    saveOriginalUrl(request,originalUrl);
            }
            ActionForward af = doAction(mapping, form, request, response);
            /*
	    if(us != null)
	    {
               boolean ifDisplayUserMessages = LoginUtil.getIfDisplayUserMessages(request);
               if(ifDisplayUserMessages)
               {
                   if(af.getRedirect())
                        request.setAttribute("messagesize",getMessageSize(us.getUserId(),request));
                   else
                        request.getSession().setAttribute("messagesize",getMessageSize(us.getUserId(),request));
               }
	    }*/
            return af;
	}
        /**
         * each concrete action class must implement this method
         * @param mapping
         * @param form
         * @param request
         * @param response
         * @return
         */
	public abstract ActionForward doAction(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception;


        /**
         * return the value of parameter action, the action name may be changed later
         * please be sure all Struts action classes use this method to get action
         * @param request
         * @return
         */

        String getAction(HttpServletRequest request)
        {
            return request.getParameter("action");
        }
        
        void saveOriginalUrl(HttpServletRequest request,String originalUrl)
        {
            request.setAttribute("originalUrl",originalUrl);
        }
        
        void saveOriginalUrl(HttpServletRequest request)
        {
            String method = request.getMethod().toLowerCase();
            String queryString = "";
            if("get".equals(method))
            {
                queryString = request.getQueryString();
                if(queryString == null)queryString = "";
            }
            if("post".equals(method))
            {
                Enumeration e = request.getParameterNames();
                String name = "";
                String value = "";
                while(e.hasMoreElements())
                {
                    name = (String)e.nextElement();
                    value = request.getParameter(name);
                    if(queryString.length() > 0)
                    {
                        queryString = queryString+"&"+name+"="+value;
                    }
                    else
                    {
                        queryString = name+"="+value;
                    }
                }
            }
            String originalUrl = request.getRequestURI()+"?"+queryString;
            request.setAttribute("originalUrl",originalUrl);
       }
       
       /**
         * retrive the size of unread messages of the user
         * @deprecated
         * @param userId
         * @return
         * @throws QaException
        */
        private int getMessageSize1(Integer userId,HttpServletRequest request) throws QaException
        {
            int messageSize = 0;
            try
            {
                if(userId == null)return 0;
                UserSession us = UserSessionUtil.getUserSession(request);
                if(us == null)return 0;
                Transaction tx = HibernateSessionFactory.getSession().beginTransaction();            
                UserDAO userDAO = new UserDAO();
                User user = userDAO.findById(userId);
                messageSize = user.getNewMessages().size();
                tx.commit();
                us.setLoginName(user.getLoginName());
                us.setScore(user.getUserScore().getTotalScore());
            }
            catch(Exception e)
            {
                throw new QaException(e);
            }
            finally
            {
                HibernateSessionFactory.closeSession();
            }
            return messageSize;
        }
       
       protected void saveErrorsAndMessages(ActionForward af,
       ActionMessages errors,ActionMessages messages,HttpServletRequest request)
       {
           if(errors.size() > 0)
           {
               if(!af.getRedirect())
               {
                   saveErrors(request, errors);
               }
               else
               {
                   saveErrors(request.getSession(), errors);
               }
           }
           if(messages.size() > 0)
           {
               if(!af.getRedirect())
               {
                   saveMessages(request, messages);
               }
               else
               {
                   saveMessages(request.getSession(), messages);
               }
           }
       }

    protected boolean checkAdminRight(UserSession us)
    {
        if(us == null)return false;
        else
        {
            if(!"1".equals(us.getType()))
            {
                return false;
            }
        }
        return true;
    }

}